import { build } from 'esbuild';
import * as fs from 'fs';
import * as path from 'path';

async function compileFiles(directory: string, outputDir: string) {
  const files = fs.readdirSync(directory);

  for (const file of files) {
    const filePath = path.join(directory, file);
    const stats = fs.statSync(filePath);

    if (stats.isDirectory()) {
      // 如果是目录，则递归处理
      const nestedOutputDir = path.join(outputDir, file);
      fs.mkdirSync(nestedOutputDir, { recursive: true });
      await compileFiles(filePath, nestedOutputDir);
    } else if (path.extname(file) === '.ts') {
      // 如果是 TypeScript 文件，则进行编译
      const outputPath = path.join(outputDir, file.replace('.ts', '.js'));
      const result = await build({
        entryPoints: [filePath],
        outfile: outputPath,
        bundle: false,
        platform: 'node',
        target: 'node12',
        format: 'cjs',
        // external: ['electron','path','fs'], // bundle为 true 时，排除 electron 模块不进行打包
      });
      console.log(`编译文件 "${filePath}" 到 "${outputPath}"`);
    }
  }
}

async function bootstrap() {
  try {
    const srcDir = 'src'; // 源代码目录，根据实际情况进行修改
    const distDir = 'dist_main'; // 输出目录，根据实际情况进行修改

    fs.mkdirSync(distDir, { recursive: true });
    await compileFiles(srcDir, distDir);

    console.log('主进程全部文件编译完成，即将启动。');
  } catch (error) {
    console.error('编译错误:', error);
    process.exit(1);
  }
}

bootstrap();
